package com.sbtr.business.publishtask.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sbtr.business.publishtask.entity.PublishPredictTask;
import com.sbtr.business.publishtask.mapper.PublishPredictTaskMapper;
import com.sbtr.business.publishtask.service.IPublishPredictTaskService;
import com.sbtr.common.PageDto;
import com.sbtr.open.publishtask.dto.PredictListDto;
import com.sbtr.open.publishtask.dto.PublishPredictTaskDto;
import com.sbtr.util.BeanCopyUtils;
import com.sbtr.util.PageDtoUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

@Transactional
@Service
public class PublishPredictTaskServiceImpl extends ServiceImpl<PublishPredictTaskMapper, PublishPredictTask>
        implements IPublishPredictTaskService {
    private static final Logger logger = LoggerFactory.getLogger(PublishPredictTaskServiceImpl.class);
//	@Autowired
//	private OSSUtil ossUtil;
//
//	@Autowired
//	private MinioUtil minioUtil;


    @Override
    public PublishPredictTaskDto findById(Long id) {
        // TODO Auto-generated method stub
        PublishPredictTask task = getById(id);
        if (task != null) {
            return BeanCopyUtils.copyProperties(task, PublishPredictTaskDto.class);
        }

        return null;
    }

    @Override
    public PublishPredictTaskDto save(PublishPredictTaskDto dto) {
        // TODO Auto-generated method stub
        PublishPredictTask publishPredictTask = BeanCopyUtils.copyProperties(dto, PublishPredictTask.class);
        saveOrUpdate(publishPredictTask);
        dto.setId(publishPredictTask.getId());
        return dto;
    }

    /*	@Override
        @RequestMapping(value = "/{id}/getResultUrl", method = RequestMethod.GET)
        public String getResultUrl(Long id) {
            // TODO Auto-generated method stub
            PublishPredictTask task = getById(id);
            if (task != null) {
                if (PublishPredictTaskDto.PREDICT_COMPLETE.equals(task.getStatus())) {
                    if (StringUtils.isNotBlank(task.getResultFile())) {
                        return ossUtil.getObjectUrl(task.getResultFile());
                    }
                }
            }
            return null;
        }
        */
/*
@Override
@RequestMapping(value = "/{id}/getResultUrl", method = RequestMethod.GET)
public String getResultUrl(Long id) {
	// TODO Auto-generated method stub
	PublishPredictTask task = getById(id);
	if (task != null) {
		if (PublishPredictTaskDto.PREDICT_COMPLETE.equals(task.getStatus())) {
			if (StringUtils.isNotBlank(task.getResultFile())) {

				String bucketName = task.getResultFile().substring(0, task.getResultFile().indexOf("/"));
				String objectName = task.getResultFile().substring(task.getResultFile().indexOf("/") + 1, task.getResultFile().length());
				try {
					return minioUtil.getObjectUrl(bucketName, objectName);
				} catch (Exception e) {
					e.printStackTrace();
					return null;
				}
			}
		}
	}
	return null;
}
*/
    @Override
    public PageDto<PublishPredictTaskDto> search(PredictListDto dto) {

        IPage<PublishPredictTaskDto> page = new Page<>();
        page.setSize(dto.getPageSize());
        page.setCurrent(dto.getPage());
        QueryWrapper<PublishPredictTaskDto> wrapper = new QueryWrapper<>();

        if (StringUtils.isNotEmpty(dto.getCreater())) {
            wrapper.eq("pt.creater", dto.getCreater());
        }
        if (null != dto.getProject_id()) {
            wrapper.eq("project_id", dto.getProject_id());
        }
        if (null != dto.getId()) {
            wrapper.like("pt.id", dto.getId());
        }
        if (StringUtils.isNotEmpty(dto.getTaskName())) {
            wrapper.like("task_name", dto.getTaskName());
        }
        if (null != dto.getStatus() && !dto.getStatus().isEmpty()) {
            wrapper.in("pt.status", dto.getStatus());
        }
        if (StringUtils.isNotEmpty(dto.getProjectName())) {
            wrapper.like("project_name", dto.getProjectName());
        }
        if (null != dto.getCreateTime()) {
            Date createTimeTo = dto.getCreateTime(); //取时间
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(createTimeTo);
            calendar.add(calendar.DATE, 1); //把日期往后增加一天,整数  往后推,负数往前移动
            createTimeTo = calendar.getTime(); //这个时间就是日期往后推一天的结果
            wrapper.between("pt.", dto.getCreateTime(), createTimeTo);
        }

        if (null != dto.getEndTime()) {
            Date createTimeTo = dto.getEndTime(); //取时间
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(createTimeTo);
            calendar.add(calendar.DATE, 1); //把日期往后增加一天,整数  往后推,负数往前移动
            createTimeTo = calendar.getTime(); //这个时间就是日期往后推一天的结果
            wrapper.between("end_time", dto.getEndTime(), createTimeTo);
        }

        wrapper.orderByDesc("id");
//		page = page(page, wrapper);
        page = baseMapper.customPage(page, wrapper);
        PageDto<PublishPredictTaskDto> pageDto = PageDtoUtils.getPageDtoByIPage(page, PublishPredictTaskDto.class);
        return pageDto;
    }


    @Override
    public PageDto<PublishPredictTaskDto> searchList(PredictListDto dto) {
        IPage<PublishPredictTaskDto> page = new Page<>();
        page.setSize(dto.getPageSize());
        page.setCurrent(dto.getPage());
        QueryWrapper<PublishPredictTaskDto> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(dto.getCreater())) {
            wrapper.eq("pt.creater", dto.getCreater());
        }
        if (null != dto.getId()) {
            wrapper.like("pt.id", dto.getId());
        }
        if (StringUtils.isNotEmpty(dto.getTaskName())) {
            wrapper.like("task_name", dto.getTaskName());
        }
        if (null != dto.getStatus() && !dto.getStatus().isEmpty()) {
            wrapper.in("pt.status", dto.getStatus());
        }
        if (StringUtils.isNotEmpty(dto.getProjectName())) {
            wrapper.like("project_name", dto.getProjectName());
        }
        if (null != dto.getCreateTime()) {
            Date createTimeTo = dto.getCreateTime(); //取时间
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(createTimeTo);
            calendar.add(calendar.DATE, 1); //把日期往后增加一天,整数  往后推,负数往前移动
            createTimeTo = calendar.getTime(); //这个时间就是日期往后推一天的结果
            wrapper.between("pt.", dto.getCreateTime(), createTimeTo);
        }

        if (null != dto.getEndTime()) {
            Date createTimeTo = dto.getEndTime(); //取时间
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(createTimeTo);
            calendar.add(calendar.DATE, 1); //把日期往后增加一天,整数  往后推,负数往前移动
            createTimeTo = calendar.getTime(); //这个时间就是日期往后推一天的结果
            wrapper.between("end_time", dto.getEndTime(), createTimeTo);
        }

        wrapper.orderByDesc("id");
//		page = page(page, wrapper);
        page = baseMapper.customPage(page, wrapper);
        PageDto<PublishPredictTaskDto> pageDto = PageDtoUtils.getPageDtoByIPage(page, PublishPredictTaskDto.class);
        return pageDto;
    }


    @Override
    public List<PublishPredictTaskDto> findByPublishId(Long publishId) {
        // TODO Auto-generated method stub
        QueryWrapper<PublishPredictTask> wrapper = new QueryWrapper<>();
        wrapper.eq("publish_id", publishId);
        wrapper.orderByDesc("create_time");
        List<PublishPredictTask> taskList = this.list(wrapper);
        if (taskList == null || taskList.isEmpty()) {
            logger.warn("部署id为{}的服务, 没有对应预测任务", publishId);
            throw new RuntimeException("部署id为" + publishId + "的服务, 没有对应预测任务");
        }

        return BeanCopyUtils.copyProperties(taskList, PublishPredictTaskDto.class);
    }

    @Override
    public Double getPredictPercent(Long id) {
        // TODO Auto-generated method stub
        PublishPredictTask task = this.getById(id);
        if (task != null) {
            return task.getPredictPrecent();
        }
        return null;
    }

}
